<template>
  <div class="normal-preview-file" v-loading.fullscreen.lock="loading">
    <PreviewFileModel
      ref="PreviewFileModelRef"
      :info="info"
      :title="title"
      @toDownload="toDownload"
    >
      <template v-if="isDocx">
        <vue-office-docx
          v-show="previewSuccess"
          :src="url"
          @error="errorHandler"
          @rendered="renderedHandler"
        />
        <iframe
          v-if="showPreview"
          id="preview-other"
          class="preview-other-type"
          :src="officeUrl"
          @load="onLoad"
        ></iframe>
      </template>

      <template v-else-if="isXlsx">
        <vue-office-excel
          v-show="previewSuccess"
          :src="url"
          @error="errorHandler"
          @rendered="renderedHandler"
        />
        <iframe
          v-if="showPreview"
          id="preview-other"
          class="preview-other-type"
          :src="officeUrl"
          @load="onLoad"
        ></iframe>
      </template>

      <div class="normal-preview-file-txt" v-else-if="isTxt">
        <pre class="normal-preview-file-txt-content">{{ officeUrl }}</pre>
      </div>

      <template v-else>
        <iframe id="preview-other" class="preview-other-type" :src="officeUrl" @load="onLoad"></iframe>
      </template>
    </PreviewFileModel>
  </div>
</template>

<script>
/* vue*/
import { defineComponent, onMounted, ref, computed, reactive, toRefs} from 'vue'
/* components*/
import PreviewFileModel from './components/PreviewFileModel.vue'
/* word*/
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'
/* excel*/
import VueOfficeExcel from '@vue-office/excel'
import '@vue-office/excel/lib/index.css'
/* util*/
import {t} from "@src/locales";
export default defineComponent({
  name: "PreviewFile",
  props: {
    info: {
      type: Object,
      default: (() => {})
    }
  },
  components: {
    PreviewFileModel,
    VueOfficeDocx,
    VueOfficeExcel,
  },
  setup(props) {
    const PreviewFileModelRef = ref()
    const loading = ref(false)

    const previewState = reactive({
      previewSuccess: false,
      showPreview: false // docx和excel通过kkFileView去预览，因为vue-office预览失败了
    });

    // 文件后缀
    const fileSuffix =  computed(() => props.info?.suffix ?? '')
    // 文件url
    const url = computed(() => props.info?.url ?? '')
    // 文件名称
    const title = computed(() => props.info?.name ?? t('common.base.preview'))

    // 判断是否是word:docx文件
    const isDocx = computed(() => ['docx'].includes(fileSuffix.value))

    // 判断是否是excel:xlsx文件
    const isXlsx = computed(() => ['xlsx'].includes(fileSuffix.value))

    // 判断是否是txt文件
    const isTxt = computed(() => ['txt'].includes(fileSuffix.value))

    const officeUrl = ref('');

    async function init() {
      try {
        loading.value = true;
        if(!isXlsx.value && !isDocx.value) {
          const response = await fetch(url.value);
          officeUrl.value = isTxt.value ? await response.text() : `/fileview/onlinePreview?url=${encodeURIComponent(Base64.encode(response.url))}`;
        }
        PreviewFileModelRef.value?.open()
      } catch (e) {
        toDownload();
        console.error(e)
      } finally {
        isTxt.value && (loading.value = false);
      }
    }

    // 下载
    function toDownload() {
      let a = document.createElement('a');
      a.href = `/files/download?fileId=${props.info.id}`;
      a.download = title.value;
      a.click();
      window.URL.revokeObjectURL(a);
    }

    // vue-office预览失败
    async function errorHandler() {
      try {
        console.log('加载失败');
        previewState.previewSuccess = false;
        //通过fileview去预览
        const response = await fetch(url.value);
        officeUrl.value = `/fileview/onlinePreview?url=${encodeURIComponent(Base64.encode(response.url))}`;
        previewState.showPreview = true;
      } catch (e) {
        toDownload();
        console.error(e);
      };
    }

    // vue-office预览成功
    function renderedHandler() {
      console.log('加载成功');
      previewState.previewSuccess = true;
      loading.value = false;
    }

    // iframe加载完成
    function onLoad() {
      loading.value = false;
    }

    onMounted( () => {
      init();
    })

    return {
      loading,
      officeUrl,
      PreviewFileModelRef,
      url,
      title,
      isDocx,
      isXlsx,
      isTxt,
      ...toRefs(previewState),
      toDownload,
      errorHandler,
      renderedHandler,
      onLoad,
    }
  }
})
</script>

<style lang="scss" scoped>
.normal-preview-file {
  .preview-other-type {
    width: 100%;
    height: 100%;
  }
  &-txt {
    height: 100%;
    overflow: auto;

    &-content {
      font-size: 12px;
      width: 1000px;
      background: white;
      word-break: break-word;
      white-space: break-spaces;
      margin: 0 auto;
      padding: 12px;
    }
  }
}
</style>
<style lang="scss">
.normal-preview-file .docx-wrapper {
  .docx {
    width: 80% !important;
  }
}
</style>